import { defineStore } from "pinia"
import router from "@/router"
import { nextTick } from "vue"

type tagType = { name: string, title: string, fullPath: string, active: boolean, affix?: boolean, [key: string]: any }

const initTags = [
  { name: 'home', title: '首页', fullPath: '/', affix: true, active: false },
]

export default defineStore('cachePages', {
  state: () => ({
    tags: JSON.parse(JSON.stringify(initTags)) as tagType[],
    maxLength: 8,
  }),
  actions: {
    addTag(tag: tagType) {
      if (this.tags.length == this.maxLength) {
        this.tags.forEach(v => v.active = false)
        return
      }
      this.tags.forEach(v => v.active = false)
      this.tags.push({ ...tag, active: true })
      nextTick(() => { this.setSortAttr() })
    },
    deleteTag(index: number) {
      const delTag = this.tags.splice(index, 1)[0]
      // fullPath会带上跳转时传递query和params参数。
      if (delTag.fullPath == router.currentRoute.value.fullPath) {
        const nextTag = this.tags[index]
        if (nextTag) router.replace(this.tags[index].fullPath)
        else router.replace(this.tags[index - 1].fullPath)

      }
      // if(router.currentRoute.name===delTag.name)
      // router.replace(state.tags[state.tags.length-1].fullPath)
    },
    activeTag({ index, fullPath }: { index: number, fullPath: string }) {
      this.tags.forEach(v => v.active = false)
      this.tags[index].active = true
      this.tags[index].fullPath = fullPath
    },
    setSort(sortNameArr: string[]) {
      const nameToTagMap: objType = {}
      this.tags.forEach(v => { nameToTagMap[v.name] = v })
      const newTags: tagType[] = []
      sortNameArr.forEach(v => { newTags.push(nameToTagMap[v]) })
      this.tags = newTags
    },
    setSortAttr() {
      const tagsDom = document.querySelectorAll('.ant-tabs-tab')
      this.tags.forEach((v, i) => {
        if(tagsDom[i]){
          tagsDom[i].setAttribute("itemId", v.name);
        }
      })
    },
    clearActive() {
      this.tags.forEach(v => v.active = false)
    },
    clearRightTags(index: number) {
      this.tags = this.tags.filter((v, i) => i <= index || v.affix)
    },
    clearLeftTags(index: number) {
      this.tags = this.tags.filter((v, i) => i >= index || v.affix)
    },
    clearOtherTags(index: number) {
      const saveTag = this.tags[index]
      this.tags = [...JSON.parse(JSON.stringify(initTags))]
      if (saveTag.name != 'home') this.tags.push(saveTag)
    },
    clearTags(isLogout = false) {
      this.tags = JSON.parse(JSON.stringify(initTags))
      if (!isLogout)
        router.replace(this.tags[0].fullPath)
    },
  },


})